<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="618">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备厂商" prop="equipmentManufacturer">
        <el-select v-model="formData.equipmentManufacturer" placeholder="请选择设备厂商">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.EQUIPMENT_MANUFACTURER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员编号" prop="memberUserId">
        <el-select
          v-model="formData.memberUserId"
          filterable
          @change="getUserEquipmentPlaceOptions"
          :filter-method="getMemberUserOptions"
          clearable
          placeholder="请输入会员昵称"
        >
          <el-option
            v-for="dict in memberUserOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="场所编号" prop="placeId" v-if="formData.memberUserId">
        <el-select v-model="formData.placeId" filterable clearable placeholder="请选择场所编号">
          <el-option
            v-for="dict in userEquipmentPlaceOptions"
            :key="dict.id"
            :label="dict.equipmentPlaceName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备序列号" prop="deviceIdentifier">
        <el-input v-model="formData.deviceIdentifier" placeholder="请输入设备序列号" />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { UserEquipmentApi, UserEquipmentVO } from '@/api/iot/userequipment'
import { getUserPage, UserVO } from '@/api/member/user'
import { UserEquipmentPlaceApi, UserEquipmentPlaceVO } from '@/api/iot/userequipmentplace'
import { JhlEquipmentDeviceVO } from '@/api/iot/jhlequipmentdevice'

/** 会员设备 表单 */
defineOptions({ name: 'UserEquipmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  equipmentManufacturer: undefined,
  deviceIdentifier: '',
  placeId: undefined,
  memberUserId: undefined,
  deviceName: '',
  memberUser: {} as UserVO,
  equipment: {} as JhlEquipmentDeviceVO
})
const formRules = reactive({
  equipmentManufacturer: [{ required: true, message: '设备厂商不能为空', trigger: 'change' }],
  deviceIdentifier: [{ required: true, message: '设备序列号不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  placeId: [{ required: true, message: '场所编号不能为空', trigger: 'blur' }],
  memberUserId: [{ required: true, message: '会员编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userEquipmentPlaceOptions = ref<UserEquipmentPlaceVO[]>([]) // 场所列表
const getUserEquipmentPlaceOptions = async (memberUserId: any) => {
  if (!memberUserId) {
    return
  }
  const data = await UserEquipmentPlaceApi.getUserEquipmentPlacePage({
    pageNo: 1,
    pageSize: -1,
    memberUserId
  })
  userEquipmentPlaceOptions.value = data.list
}
const memberUserOptions = ref<UserVO[]>([]) // 会员列表
const getMemberUserOptions = async (query: string) => {
  const data = await getUserPage({
    pageNo: 1,
    pageSize: 20,
    nickname: query
  })
  memberUserOptions.value = data.list
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '绑定设备'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserEquipmentApi.getUserEquipment(id)
      formData.value.deviceIdentifier = formData.value.equipment.deviceIdentifier
      formData.value.deviceName = formData.value.equipment.deviceName
      await getMemberUserOptions(formData.value.memberUser.nickname || '')
      await getUserEquipmentPlaceOptions(formData.value.memberUserId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserEquipmentVO
    if (formType.value === 'create') {
      await UserEquipmentApi.createUserEquipment(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserEquipmentApi.updateUserEquipment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    equipmentManufacturer: undefined,
    deviceIdentifier: '',
    placeId: undefined,
    memberUserId: undefined,
    deviceName: '',
    memberUser: {} as UserVO,
    equipment: {} as JhlEquipmentDeviceVO
  }
  formRef.value?.resetFields()
}
</script>
